import Request from '@/plugins/luch-request/index.js';
import { tip } from "../utils/modules/system.js";

const http = new Request();

/**
 * @description 修改全局默认配置
 * @param {Function}   
 */
http.setConfig((config) => { /* config 为默认全局配置*/
	/* 根域名 */
	config.baseURL = "https://api.sxbchr.com/bchr";
	// 默认开启 showLoading
	config.custom = {
		showLoading: true
	}
	config.header = {
		// contentType: "application/x-www-form-urlencoded"
		'Content-Type': 'application/json'
	}
	return config
})


/**
 * 在请求之前拦截
 */
http.interceptors.request.use((config) => {
	config.header = {
		...config.header,
		"X-Access-Token": uni.getStorageSync("token") || ""
	}
	return config
}, config => {
	return Promise.reject(config)
})


// 响应拦截
http.interceptors.response.use((res) => {
	console.log(res)
	if(res.statusCode === 200){
		if(res.data.code === 200){
			if(res.config.url === "/app/config/uploadBase64"){
				return res.data.message;
			}else{
				return res.data.result;
			}
		}else if(res.data.code === 401){
			uni.removeStorageSync("token");
			uni.navigateTo({
				url: "pages/login"
			})
		}else{
			tip(res.data.message);
			return Promise.reject(res.data.message)
		}
	}else{
		return Promise.reject("error")
	}
}, error => {
	//获取状态码
	const status = error.data.code || error.statusCode || undefined;
	if (status == 401) {
		uni.removeStorageSync("token");
		uni.navigateTo({
			url: "pages/login"
		})
	}
	return Promise.reject("服务忙，请稍后再试")
});


export default http;